import {
  NextFunction,
  Request,
  Response,
} from 'express';
import jwt from 'jsonwebtoken';

import { User } from '../models/user.model';
import { EnumStatusCode } from '@shared/constant/enum';

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

// 扩展 Request 接口以包含用户信息
declare global {
  namespace Express {
    interface Request {
      user?: {
        user_id: string;
        username: string;
        role: string;
      };
    }
  }
}

// JWT 认证中间件
export const authenticateToken = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.startsWith('Bearer ') 
      ? authHeader.substring(7) 
      : authHeader;

    if (!token) {
      return res.status(EnumStatusCode.UNAUTHORIZED).json({
        code: EnumStatusCode.UNAUTHORIZED,
        message: '未提供认证令牌',
        data: null
      });
    }

    // 验证 token
    const decoded = jwt.verify(token, JWT_SECRET) as any;
    
    // 检查用户是否仍然存在且状态正常
    const user = await User.findById(decoded.userId);
    if (!user) {
      return res.status(EnumStatusCode.UNAUTHORIZED).json({
        code: EnumStatusCode.UNAUTHORIZED,
        message: '用户不存在',
        data: null
      });
    }

    if (user.status === 'disabled') {
      return res.status(EnumStatusCode.UNAUTHORIZED).json({
        code: EnumStatusCode.UNAUTHORIZED,
        message: '账户已被禁用',
        data: null
      });
    }

    // 将用户信息添加到请求对象中
    req.user = {
      user_id: decoded.userId,
      username: decoded.username,
      role: decoded.role
    };

    next();
  } catch (error) {
    if (error instanceof jwt.TokenExpiredError) {
      return res.status(EnumStatusCode.UNAUTHORIZED).json({
        code: EnumStatusCode.UNAUTHORIZED,
        message: '认证令牌已过期',
        data: null
      });
    } else if (error instanceof jwt.JsonWebTokenError) {
      return res.status(EnumStatusCode.UNAUTHORIZED).json({
        code: EnumStatusCode.UNAUTHORIZED,
        message: '无效的认证令牌',
        data: null
      });
    } else {
      console.error('认证中间件错误:', error);
      return res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
        code: EnumStatusCode.INTERNAL_SERVER_ERROR,
        message: '认证失败',
        data: null
      });
    }
  }
};

// 管理员权限检查中间件
export const requireAdmin = (req: Request, res: Response, next: NextFunction) => {
  if (!req.user) {
    return res.status(EnumStatusCode.UNAUTHORIZED).json({
      code: EnumStatusCode.UNAUTHORIZED,
      message: '未认证用户',
      data: null
    });
  }

  if (req.user.role !== 'admin') {
    return res.status(EnumStatusCode.FORBIDDEN).json({
      code: EnumStatusCode.FORBIDDEN,
      message: '需要管理员权限',
      data: null
    });
  }

  next();
};

// 可选的认证中间件（不强制要求登录）
export const optionalAuth = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.startsWith('Bearer ') 
      ? authHeader.substring(7) 
      : authHeader;

    if (token) {
      const decoded = jwt.verify(token, JWT_SECRET) as any;
      const user = await User.findById(decoded.userId);
      
      if (user && user.status === 'active') {
        req.user = {
          user_id: decoded.userId,
          username: decoded.username,
          role: decoded.role
        };
      }
    }

    next();
  } catch (error) {
    // 可选认证失败时不阻止请求继续
    next();
  }
};
